<template>
  <view class="warp">
    <!-- 页面顶部 -->
    <view class="top" :style="{height: 'calc(440rpx + '+StatusBar+'px)'}">
      <image class="bg" :src="imgWechatUrl+'/user/login-bg.png'" mode="aspectFill"></image>
      <image class="logo" src="/static/logo.png" mode="aspectFill" />
      <view class="name">酒氏酒</view>
    </view>
    <view class="main">
      <!-- 微信登录按钮 start -->
      <view class="login-btn" @click="wxLogin">
        <image class="wx-pic" :src="imgWechatUrl+'/user/wx-btn.png'" mode="aspectFit" />
        <text class="text-lg margin-left-sm">{{ i18n['微信登录'] }}</text>
      </view>
      <!-- 微信登录按钮 end -->
      <!-- 手机号登录 start -->
      <view class="phone-btn" @click="goLoginPhone">{{ i18n['手机号登录'] }}</view>
      <!-- 手机号登录 end -->
    </view>
    <!-- 隐私政策 start -->
    <view class="privacy">
      <view @click="changeCheck" class="checkbox-img flex align-center">
        <image class="img" mode="aspectFit" :src="imgWechatUrl+'/user/check.png'" v-if="check"></image>
        <image class="img" mode="aspectFit" :src="imgWechatUrl+'/user/unchecked.png'" v-else></image>
      </view>
      <text class="text-sm text-666">
        {{ i18n['阅读并同意'] }}
        <text class="action" @click="goAhreement(1)">{{ i18n['《用户注册协议》'] }}</text>
        {{ i18n['与'] }}
        <text class="action" @click="goAhreement(2)">{{ i18n['《隐私政策》'] }}</text>
      </text>
    </view>
    <!-- 隐私政策 end -->
    <!-- 断网监测 start -->
    <fu-notwork></fu-notwork>
    <!-- 断网监测 end -->
  </view>
</template>

<script>
// 引入验证方法
import { validate } from '@/common/utils/index';
export default {
  data() {
    return {
      phone: '', // 手机号,@String
			imgWechatUrl:this.imgWechatUrl,
      vercode: '', // 验证码,@String
      is_click: false, // 立即登录按钮是否点击,@Boolean
      verCodeBtnLoading: false, // 是否显示加载图标,@Boolean
      time: 60, // 倒计时60S,@Number
      beginning: false, // 显示倒计时,@Boolean
      PAGE_BASE_URL: '/pages/user/login/', // 页面基础路径,@String
      timer: null, // 计时器,@Function
      check: false
    };
  },
  onUnload() {
    // 页面关闭时清除计时器，优化性能
    clearInterval(this.timer);
  },
  methods: {
    /**
     * @event
     * @description 去手机号登陆
     */
    goLoginPhone() {
      // this.$urouter.navigateTo('/pages/user/login/query-login/index')
      uni.redirectTo({
        url:'/pages/user/login/query-login/index'
      })
    },
    /**
     * @event
     * @description 去协议
     */
    goAhreement(val) {
      // uni.navigateTo({
      //   url: '/pages/user/login/user-agreement/index?id='+val
      // })
      this.$urouter.navigateTo({
        url: '/pages/user/login/user-agreement/index',
        params: {
          id: val
        }
      });
    },
    /**
     * @event
     * @description 是否同意用户协议
     */
    changeCheck() {
      this.check = !this.check;
    },
    BackPage() {
      uni.navigateBack({
        delta: 1
      });
    },
    /**
     * @event 发送验证码
     */
    handleSendVerCode() {
      // 保存this
      let _this = this;
      // 从this里结构出来phone
      let { phone } = this;

      // 验证手机号strat
      if (!phone) {
        this.$message.info(this.i18n['请输入手机号']);
        return false;
      }
      if (!validate(phone, 'phone')) {
        this.$message.info(this.i18n['请正确输入手机号']);
        return false;
      }
      // 验证手机号 end

      // 如果有倒计时，return false
      if (this.beginning) return false;

      this.verCodeBtnLoading = true; // 显示加载状态
     

      /**
       * @desc 请求验证码接口
       * @param {Object} {} - 参数
       * @param {Boolean} {}.is_test - 是否是测试环境
       * @param {String} {}.mobile - 手机号
       * @param {String} {}.type - 类型
       */
      this.$api
        .post(global.apiUrls.GetVerifyCode, {
          is_test: global.IS_DEV,
          mobile: phone,
          type: '3'
        })
        .then(res => {
          // 改加载状态为false
          _this.verCodeBtnLoading = false;

          // 如果后台返回的code码为1
          if (res.data.code == 1) {
            // 清除倒计时,防抖作用
            clearInterval(_this.timer);
             this.beginning = true; // 显示倒计时
            _this.timer = setInterval(() => {
              if (_this.time == 1) {
                //倒计时结束就清楚这个倒计时
                clearInterval(_this.timer);
                _this.time = 60; // 倒计时60s
                _this.beginning = false; // 是否显示倒计时改为false
                return;
              }
              _this.time--;
            }, 1000);
            // 向用户发送提示
            if(res.data.data.code) _this.$message.info(_this.i18n['验证码为'] + res.data.data.code );
          } else {
            // 如果报错，向用户提示
            _this.$message.info(res.data.msg);
          }
        })
        .catch(function(err) {
          // 接口错误打印错误
          console.log(err);
        });
    },
    /**
     * @event 跳转到邮箱登录页面
     */
    emailLogin() {
      uni.redirectTo({
        url: '/pages/user/login/login-email-code/index'
      });
    },
    /**
     * @event 微信登陆
     */
    wxLogin() {
			if (!this.check) {
				this.$message.info(this.i18n['请阅读并勾选页面协议']);
				return false;
			}
      let _this = this;
      // #ifdef APP-PLUS
      // 如果是app环境打开微信
      if (
        plus.runtime.isApplicationExist({
          pname: 'com.tencent.mm',
          action: 'weixin://'
        })
      ) {
        uni.getProvider({
          service: 'oauth',
          success: function(res) {
            console.log(res);
            // 如果支持微信等，就执行 wx_login_fn 方法
            if (~res.provider.indexOf('weixin')) {
              console.log("???")
              _this.wx_login_fn();
            }
          },
          fail: function(err) {
            // api错误是打印错误
            console.log(err);
          }
        });
      } else {
        // 调起失败时提醒用户
        this.$message.info(this.i18n['请安装微信后再使用此功能']);
      }
      // #endif
    },
    /**
     * @function 微信授权登录
     */
    wx_login_fn() {
      uni.login({
        provider: 'weixin',
        success: (loginRes) => {
          uni.getUserInfo({
            provider: 'weixin',
            success: (infoRes) => {
              console.log('login',loginRes);
              console.log('getUserInfo',infoRes);
              let { nickName, avatarUrl, gender,unionId } = infoRes.userInfo;
              let clientId = plus.push.getClientInfo().clientid || '';
              console.log('clientId', clientId);
              let appSystem = uni.getSystemInfoSync().platform == 'ios' ? 1 : 2;
              console.log('appSystem',appSystem)
              console.log('unionId',unionId);
              let data = {
                type: 1,
                clientId: clientId || '',
                appSystem: appSystem || '',
                nickname: nickName,
                avatar: avatarUrl,
                gender: gender,
                wx_unionid: unionId,
              }
              this.$api
                .post(global.apiUrls.postUserSocialLogin, data)
                .then(res => {
                  // 保存用户信息
                  res = res.data;
                  console.log('??????',res);
                  if (res.code == 1) {
                    this.$message.info(res.msg);
                    this.$store.commit('updateUserInfo', res.data.userinfo);
                    setTimeout(() => {
                      uni.navigateBack({delta: this.delta});
                    }, 800);
                  } else if (res.code == -999) {
                    // 未注册过的用户
                    this.$urouter.redirectTo({
                      url: '/pages/user/login/bind-phone/index',
                      params: {
                        unionId: unionId,
                        sex: gender,
                        nickName: nickName,
                        avatarUrl: avatarUrl,
                        authType: 'wx_unionid',
                      }
                    });
                    // 点击手机号账号登录按钮
                  } else if (res.code == -1) {
                    this.$message.info(res.msg);
                  }
                })
                .catch(err => {
                  uni.hideLoading();
                  console.log(err);
                });
            }
          });
        },
        error: function(err) {
          uni.hideLoading();
          console.log(err);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.warp {
  position: relative;
  background: #FFFFFF;
  height: 100vh;
  .top{
    height: 480rpx;
    position: relative;
    .bg{
      width: 100%;
      height: 100%;
    }
    .logo{
      width: 180rpx;
      height: 180rpx;
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
    }
    .name{
      font-size: 40rpx;
      color: #333333;
      position: absolute;
      bottom: -88rpx;
      left: 50%;
      transform: translateX(-50%);
    }
  }
  .main{
    margin-top: 288rpx;
    .login-btn{
      width: 638rpx;
      height: 88rpx;
      background: $bgtheme;
      border-radius: 50rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #FFFFFF;
      margin: 0 auto;
      .wx-pic{
        width: 44rpx;
        height: 44rpx;
      }
    }
    .phone-btn{
      width: 638rpx;
      font-size: 28rpx;
      color: #333333;
      margin: 32rpx auto;
      text-align: center;
    }
  }
  .privacy{
    width: 100%;
    display: flex;
    position: fixed;
    bottom: 40rpx;
    bottom: calc(40rpx + constant(safe-area-inset-bottom));
    bottom: calc(40rpx + env(safe-area-inset-bottom));
    justify-content: center;
    align-items: center;
    font-size: 24rpx;
    .checkbox-img{
      width: 24rpx;
      margin-right: 8rpx;
      .img{
        width: 24rpx;
        height: 24rpx;
        // margin-top: -1rpx;
      }
    }
    .action{
      color: #4177DD;
    }
  }
}
</style>
